﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using MySql.Data.MySqlClient;
using System.Threading;


namespace SimoBotGUI
{
    /*
    class UserMsgEventArgs : EventArgs
    {
        public string message;

        public UserMsgEventArgs(string msg)
        {
            message = msg;
        }
    }
     */

    class SimoBotEngine
    {
        public frmMain MainForm;
        string server;
        int port;
        string channel;
        string nick;
        BackgroundWorker worker;
        public SimoBotEngine(string Server, int Port, string Channel, string Nick, frmMain formMain, BackgroundWorker workar)
        {
            server = Server;
            port = Port;
            channel = Channel;
            nick = Nick;
            MainForm = formMain;
            worker = workar;
        }
        //frmConnect ConnectInfo = new frmConnect();
        /*
        public delegate void UserMsgEventHandler(object sender, EventArgs e);

        public event UserMsgEventHandler UserMsgEvent;

        protected virtual void OnUserMsgEvent(EventArgs e)
        {
            // Just call the associated delegates
            if (UserMsgEvent != null)
                UserMsgEvent(this, e);
        }
         */
        /*
        private void UserMsg(string msg)
        {
            UserMsgEvent(this, new UserMsgEventArgs((msg)));
        }
        */
        
        public void initConnect()
        {
            Connect(server, port, channel, nick);
        }

        string SharedMessage;
        private void ShareMsg(string msg)
        {
            SharedMessage = msg + " " + DateTime.Now.Millisecond;
        }

        public string GetSharedMessage()
        {
            string TimeStampedMsg = SharedMessage;
            return TimeStampedMsg;
        }

        private void NewMessage(string NewMsg)
        {
            ShareMsg(NewMsg);
            worker.ReportProgress(1);
        }

        public string pingPong(string[] outputArray, int i)
        {
            string pong = "PONG :" + outputArray[i].Replace(":", null);
            //NewMessage("***Ponged:" + pong + "***");                           //tells thy user that simo actually managed to pong. It should work now, so no need to tell.
            return pong;
        }
        public void Connect(string server, int port, string channel, string nick)
        {

            TcpClient tcpClient;
            NetworkStream networkStream;
            StreamReader ircReader;
            StreamWriter ircWriter;

            tcpClient = new TcpClient(server, port);
            networkStream = tcpClient.GetStream();
            ircReader = new StreamReader(networkStream, Encoding.Default);
            ircWriter = new StreamWriter(networkStream, Encoding.Default);
            ircWriter.AutoFlush = true;

            ircWriter.WriteLine("USER " + nick + " 8 * :" + nick);
            ircWriter.WriteLine("NICK " + nick);
            ircWriter.WriteLine("JOIN " + channel);

            //Initializing finished, starting looping etc.
            //--------------------------------------------------------------------------------------------------------------------------------------------
            string output = "asdf";
            int i;
            try
            {
                do
                {
                    output = ircReader.ReadLine();
                    string[] outputArray = output.Split(null);


                    NewMessage(output); //a msg visible to the user. Also handles notifying the GUI that there's a new message.
                    
                    //Analyzing the text begins.
                    if (output.Contains("/MOTD"))
                    {
                        ircWriter.WriteLine("JOIN " + channel);
                        ircWriter.WriteLine("PRIVMSG " + channel + " soup");  //353 is the irc code for channel's nicklist BTW
                    }

                    //Pongs back the ping to the server.
                    if (output.Contains("PING"))   //&& i + 1 < outputArray.Length && irkbot.IndexExists(outputArray, i - 1) == false)
                    {                                                        // ^ Some old relics, possibly but unlikely useful. ^
                        ircWriter.WriteLine(pingPong(outputArray, outputArray.Length - 1));
                    }


                    /*
                    if (output.StartsWith(":"))     // Means an user message
                    {
                        if (output.Contains("005")) { break; }                          THIS CHECKS WHETHER THE MESSAGES COME FROM USERS NOT THE SERVER. 
                        else                                                        WILL START ON THIS PART WHEN FINISHED MAKING THE BOT ACTUALLY RUNNABLE.
                        {
                            if (outputArray[i].Contains("PRIVMSG"))
                            {
                            }
                        }
                    }
                    */


                    //actually joins a channel etc. after server motd received.



                }
                while (output != null);
            }
            catch (Exception e)
            {
                NewMessage("*Unexpected error - " + e.Message + "\n");
                tcpClient.Close();
                networkStream.Close();
                ircReader.Close();
            }

        }
    }
}
